package com.example.demo.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.pojo.Result;
import com.example.demo.utils.JwtUtils;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter(urlPatterns = "/*")
public class Logincheckfileter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        1.获取请求url
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;
        String url=req.getRequestURL().toString();
        if(url.contains("login")){
            chain.doFilter(request,response);
            return;
        }
        if(url.contains("captcha")){
            chain.doFilter(request,response);
            return;
        }
        String jwt=req.getHeader("token");
        if(!StringUtils.hasLength(jwt)){
            Result error=Result.error("NOT_LOGIN");
//            手动转换  对象-json     引入阿里巴巴fastJSON
            String notLogin= JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;


        }
        try {
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){
            e.printStackTrace();
            Result error=Result.error("NOT_LOGIN");
//            手动转换  对象-json     引入阿里巴巴fastJSON
            String notLogin= JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }
        chain.doFilter(request,response);

    }
}
